<?php

namespace App\Model;

use App\Comment\Comment;
use Illuminate\Database\Eloquent\Model;

class MallOrder extends Model
{
    public $timestamps = false;
    protected $table = 'mall_order';

    /**
     * 获取订单列表
     * @param string $order_sn
     * @param string $table_sn
     * @param array $between
     * @param array $state
     * @return mixed
     */
    public function getOrderList($order_sn = '', $table_sn='', $between=[], $state=[1,2,3,4,5])
    {
        $list = MallOrder::where(['store_id' => Comment::getBizId()])
            -> whereIn('order_state', $state);
        if (!empty($order_sn)){
            $list -> where(['order_sn' => $order_sn]);
        }
        if (!empty($table_sn)){
            $list -> where('table_name', 'like', "%{$table_sn}%");
        }
        if (!empty($between)){
            $list = $list -> whereBetween('add_time', $between);
        }
        $list = $list -> orderBy('add_time', 'desc')->paginate(20)->toArray();
        if (!empty($list['data'])){
            foreach ($list['data'] as $key => $value){
                $list['data'][$key]['add_time'] = date("Y-m-d H:i:s", $value['add_time']);
            }
        }
        return $list;
    }

    /**
     * 获取当日的营业额
     * @param int $id 商户的主键ID
     * @param string $start 开始时间
     * @param string $end 结束时间
     * @return mixed
     */
    public function getTodayTurnover($id, $start='', $end='')
    {
        if ($start === '' || $end === ''){
            $today = date('Y-m-d', time());
            $start_date = $today." 00:00:00";
            $end_date = $today." 23:59:59";
        }else{
            $start_date = $start." 00:00:00";
            $end_date = $end." 23:59:59";
        }
        $list = $this -> where(['mall_order.store_id' => $id])
            -> whereBetween('mall_order.add_time', [strtotime($start_date), strtotime($end_date)])
            -> leftJoin('mall_order_fee', function ($join){
                $join -> on('mall_order.order_id', '=', 'mall_order_fee.order_id');
            })
            -> select('mall_order.*', 'mall_order_fee.wxpay', 'mall_order_fee.alipay', 'mall_order_fee.card', 'mall_order_fee.cash', 'mall_order_fee.charge')
            -> get();
        return $list;
    }
}
